//
//  CN_VideoHelper.swift
//  Voice
//
//  Created by 卢逢卫 on 2024/3/1.
//

import Foundation
import UIKit
import AVFoundation
import AVKit

public class CN_VideoHelper {

    public class func thumbImageFrom(url: URL, image: @escaping (UIImage?) -> ()) {
        let asset = AVAsset(url: url)
        let generator = AVAssetImageGenerator(asset: asset)
        generator.appliesPreferredTrackTransform = true
        let time = CMTime(seconds: 0.0, preferredTimescale: 1)
        
        generator.generateCGImagesAsynchronously(forTimes: [NSValue(time: time)]) { _, cgImage, _, _, _ in
            if let cgImage = cgImage {
                let thumbnail = UIImage(cgImage: cgImage)
                DispatchQueue.main.async {
                    image(thumbnail)
                }
            } else {
                DispatchQueue.main.async {
                    image(nil)
                }
            }
        }
    }

    public class func playVideo(videoUrl: String, presentStyle: UIModalPresentationStyle = .overFullScreen, controller: UIViewController, animated: Bool = true, completion: (() -> Void)? = nil) {
        guard let url = URL(string: videoUrl) else {
            return
        }
        
        let player = AVPlayer(url: url)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        playerViewController.modalPresentationStyle = presentStyle
        
        controller.present(playerViewController, animated: animated) {
            playerViewController.player?.play()
            completion?()
        }
    }

    public class func getFileSize(url: URL) -> String {
        do {
            let attributes = try FileManager.default.attributesOfItem(atPath: url.path)
            if let fileSize = attributes[FileAttributeKey.size] as? Double {
                let byteCountFormatter = ByteCountFormatter()
                byteCountFormatter.allowedUnits = [.useKB, .useMB, .useGB]
                byteCountFormatter.countStyle = .file
                return byteCountFormatter.string(fromByteCount: Int64(fileSize))
            }
        } catch {
            print("Error: \(error)")
        }
        
        return ""
    }

    public class func getVideoLength(videoUrl: URL) -> String {
        let asset = AVAsset(url: videoUrl)
        let duration = asset.duration
        let seconds = CMTimeGetSeconds(duration)
        
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.hour, .minute, .second]
        formatter.unitsStyle = .positional
        
        return formatter.string(from: seconds) ?? ""
    }
    
    public class func getVideoSecondsLength(videoUrl: URL) -> Double {
        let asset = AVAsset(url: videoUrl)
        let duration = asset.duration
        let seconds = CMTimeGetSeconds(duration)
        
        return seconds
    }

    public class func convertVideoFormatFrom(url: URL, toURL: URL, videoFormat: AVFileType, presetName: String? = AVAssetExportPresetMediumQuality, completeHandler: @escaping (AVAssetExportSession?) -> ()) {
        let asset = AVAsset(url: url)
        guard let exportSession = AVAssetExportSession(asset: asset, presetName: presetName!) else {
            completeHandler(nil)
            return
        }
        
        exportSession.outputURL = toURL
        exportSession.outputFileType = videoFormat
        
        exportSession.exportAsynchronously {
            completeHandler(exportSession)
        }
    }
}
